import React from "react";
import "./UserCenter.less";
import { NavBar, List, Button, Toast } from "antd-mobile";
import axios from '../../utils/http';

export default function UserCenter(props) {
    //声明一个状态
    let [user, setUser] = React.useState({});

    //模拟生命周期钩子
    React.useEffect(() => {
        //声明一个异步函数
        async function check(){
            //发送请求
            let result = await axios.post('/login/verify');
            console.log(result);
            if(result.data.code === 20000){
                //设置用户的个人信息
                setUser(result.data.data)
            }else{
                //跳转至登录页面
                props.history.push('/login');
            }
        }
        check();
    }, []);

    //声明函数
    const logout = async () => {
        //发送请求
        let result = await axios.post('/logout', {_id: user._id});
        //判断
        if(result.data.code === 20000){
            Toast.show({
                icon: 'success',
                content: '退出成功',
            });
            //跳转
            props.history.push('/login')
        }else{
            Toast.show({
                icon: 'fail',
                content: '退出异常',
            });
        }
        
    }

    return (
        <div className="user-container">
            <NavBar back={null}>个人中心</NavBar>
            {/* 内容区 start */}
            <div className="content">
                {/* 图片展示 start */}
                <div className="img">
                    <img src={user.avatar} alt="" />
                    <p className="welcome">欢迎, 用户 {user.username}</p>
                </div>
                {/* 图片展示 end */}
                <div className="h-20"></div>
                {/* 个人信息 start */}
                <div className="profile">
                    <List>
                        <List.Item>
                            <span>昵称</span>
                            <span>{user.nickName}</span>
                        </List.Item>
                        <List.Item>
                            <span>手机</span>
                            <span>{user.phone}</span>
                        </List.Item>
                    </List>
                </div>
                {/* 个人信息 end */}
                <div className="h-20"></div>
                <div className="h-20"></div>
                <Button size="large" color="danger" block={true} onClick={logout}>
                    退出登录
                </Button>
            </div>
            {/* 内容区 end */}
        </div>
    );
}
